<?php

namespace app\api\controller;


use app\common\model\AddressModel;
use app\common\model\OrderModel;
use app\common\module\Wechat;
use think\console\command\make\Model;
use think\Db;
use think\Validate;

class Order extends Common
{
    //下单
    public function unified_order(){
        $data = $this->checkSign(true);
        $res = Validate::make()
            ->rule([
                'type_id|回收分类'=>"require|in:1,2,3,4",
                'address_id|地址'=>"require|number|max:11",
                'weight_type|重量类型' =>'require|in:1,2,3',
                'date|预约日期'=>'require|date',
                'time|预约时间'=>'require|dateFormat:H:i',
                'remarks|备注'=>"max:200"
            ])->message(['location.require'=>'请框选区域']);
        if (!$res->check($data)) {
            return  clientReturnJson('10006',$res->getError());
        }
        $addModel = new AddressModel();
        $addressInfo = $addModel->where('id',$data['address_id'])->where('user_id',$data['user_id'])->find();
        if(!$addressInfo){
            return  clientReturnJson('10005','地址未找到');
        }
        $regId = $addModel->findRegion($addressInfo['latitude'],$addressInfo['longitude']);
        if(!$regId){
            return  clientReturnJson('10005','当前区域未开通!');
        }
        if($regId['open'] ==0){
            return  clientReturnJson('10005','当前区域未开通。');
        }
        $recycling_type = Db::name('recycling_type')->cache(true)->where('id',$data['type_id'])->field('title,id')->find();
        if(!$recycling_type){
            return  clientReturnJson('10005','回收类型未找到');
        }
        $this->preventSubmit($data['user_id'],5);
        $orderInfo = [
            'user_id'=>$data['user_id'],
            'headimgurl'=>$data['headimgurl'],
            'order_number'=>date("YmdHis").createCode(5),
            'type_id'=>$recycling_type['id'],
            'type_name'=>$recycling_type['title'],
            'true_name'=>$addressInfo['true_name'],
            'address'=>$addressInfo['address'],
            'address_type'=>$addressInfo['type'],
            'floor_address'=>$addressInfo['floor_address'],
            'address_name'=>$addressInfo['address_name'],
            'phone'=>$addressInfo['phone'],
            'remarks'=>$data['remarks']??'',
            'all_type'=>$data['all_type']??'[]',
            'weight_type'=>$data['weight_type'],
            'latitude'=>$addressInfo['latitude'],
            'longitude'=>$addressInfo['longitude'],
            'images'=>json_encode($data['images']),
            'order_status'=>0,
            'appointment_date'=>$data['date'],
            'appointment_time'=>$data['time'],
            'region_id'=>$regId['region_id'],
            'region_name'=>$regId['name'],
           'create_time'=>date("Y-m-d H:i:s"),
        ];
        $model = new OrderModel();
        $result = $model->add($orderInfo);
        //通知回收员接单
        $users = Db::name('users')->where(['region_id'=>$regId['region_id'],'is_out'=>0,'is_lock'=>0])
            ->field('public_openid')->select();
        $wx = new Wechat();
        foreach ($users as $v){
            if($v['public_openid']);
                $wx->sendReceiveMsg($v['public_openid'],
                $data['date'].' '.$data['time'],
                $addressInfo['address'].$addressInfo['address_name'],
                $addressInfo['true_name'],$addressInfo['phone']);
        }
        return checkRes($result,'下单');
    }
    public function getOrderList(){
        $data =$this->checkSign();
        $model = new OrderModel();
        $users_id = isset($data["users_id"])?$data["users_id"]:$data['user_id'];
        $list = $model->getOrderListByUserId($users_id,$data['status']??0);
        return package(0,'success',$list);
    }
    public function getOrderInfo(){
        $userData = $this->checkSign();
        $id = intval($userData['id']??0);
        $where = [
            ['is_delete','=',0],
            ['id','=',$id],
            ['user_id','=',$userData['user_id']]

        ];
        $info = Db::name('orders')
            ->where($where)->find();
        if($info['order_status'] ==2){
            $info['details'] =Db::name('order_detail')->where('order_id',$info['id'])->field('small_type_name,price,number,unit')->select();
        }
        return package(0,'获取成功',$info);
    }
    public function cancelOrder(){
        $data =$this->checkSign();
        $model = new OrderModel();
        $order_id = intval($data['id']??0);
        return checkRes($model->cannelOrder($data['user_id'],$order_id),'取消订单');
    }
    //评价

    public function appraise(){
        $user_data = $this->checkSign();
        $res = Validate::make()
            ->rule([
                'receiving|接单速度'=>"require|number|between:1,5",
                'come|上门速度'=>"require|number|between:1,5",
                'service|服务态度' =>'require|between:1,5',
                'comment|文字评价'=>'require|max:200',
                'order_id|订单号'=>"require|number|max:11"
            ])->message(['location.require'=>'请框选区域']);
        if (!$res->check($user_data)) {
            return  package('10006',$res->getError());
        }
        $info = Db::name('orders')
            ->where(['id'=>$user_data['order_id'],'user_id'=>$user_data['user_id']])
            ->field('accept_user_id,accept_user_name,order_status,is_appraise')
            ->find();
        if(!$info){
            return package(10005,'订单不存在');
        }
        if($info['is_appraise'] ==1){
            return package(10005,'订单重复评价');
        }
        if($info['order_status'] !=2){
            return package(10005,'订单状态错误！');
        }
        $array = [
            'user_id'=>$user_data['user_id'],
            'headimgurl'=>$user_data['headimgurl'],
            'accept_user_id'=>$info['accept_user_id'],
            'receiving'=>$user_data['receiving'],
            'come'=>$user_data['come'],
            'service'=>$user_data['service'],
            'describe'=>$user_data['comment'],
            'order_id'=>$user_data['order_id'],
            'accept_user_name'=>$info['accept_user_name'],
            'create_time'=>date("Y-m-d H:i:s")
        ];
        $result = Db::name('order_appraise')->insert($array);
        return checkRes($result,'评价');
    }
}